package cn.rubintry.bug.ui.components

import android.annotation.SuppressLint
import android.content.Context
import android.util.AttributeSet
import androidx.recyclerview.widget.RecyclerView

class MaxHeightRecyclerView : RecyclerView {
    private var maxHeight: Int = -1

    constructor(context: Context) : super(context){
        initTypedArr(context , null)
    }
    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs){
        initTypedArr(context , attrs)
    }
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    ){
        initTypedArr(context , attrs)
    }

    @SuppressLint("Recycle")
    private fun initTypedArr(context: Context, attrs: AttributeSet?) {
        val typedArray = context.obtainStyledAttributes(attrs, R.styleable.MaxHeightRecyclerView)
        maxHeight = typedArray.getDimensionPixelOffset(R.styleable.MaxHeightRecyclerView_android_maxHeight , 0)
        typedArray.recycle()
    }

    override fun onMeasure(widthSpec: Int, heightSpec: Int) {
        super.onMeasure(widthSpec, heightSpec)
        val mHeight = measuredHeight
        if(maxHeight != -1 && mHeight > maxHeight){
            setMeasuredDimension(measuredWidth , maxHeight)
        }else{
            setMeasuredDimension(measuredWidth , mHeight)
        }
    }
}